package com.webex.ta.hydra.gui.action;

import com.webex.ta.hydra.core.KeywordRegistry;
import com.webex.ta.hydra.core.engine.ResultCollector;
import com.webex.ta.hydra.gui.GuiPackage;
import com.webex.ta.hydra.gui.project.HydraProjectSuite;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-6
 * Time: 9:00:09
 */
public class CloseAction implements ActionHandler {
    private static Set<String> commands = new HashSet<String>();

    static {
        commands.add(ActionNames.CLOSE);
    }

    public Set<String> getActionNames() {
        return commands;
    }

    public void doAction(ActionEvent e) {
        performAction(e);
    }

    static int performAction(ActionEvent e) {
        HydraProjectSuite project = GuiPackage.getInstance().getActiveProject();
        return closeProject(project);
    }

    static void closeProject(ActionEvent e) {
		GuiPackage gp = GuiPackage.getInstance();

		// Clear the name of the test plan file
		gp.setTestPlanFile(null);
		gp.getIdeFrame().removeProject(gp.getActiveProject());

        // Steps to take after close

        KeywordRegistry.getInstance().unloadAllMacros();
//        gp.getHydraTable().resetUndoManager();
        ResultCollector.getInstance().clear();
	}

    public static int closeProject(HydraProjectSuite project) {
        if (project == null) return JOptionPane.YES_OPTION;
        project.getEditorPane().stopEdit();
        if (project.isDirty()) {
            int response;
            if ((response = JOptionPane.showConfirmDialog(GuiPackage.getInstance().getIdeFrame(),
                    "There are test items that have not been saved.  Do you wish to save before clearing the test plan?",
                    "Save?",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE)) == JOptionPane.YES_OPTION) {
                ActionRouter.getInstance().doActionNow(new ActionEvent(GuiPackage.getInstance().getIdeFrame(), 0, ActionNames.SAVE));
            }
            if (response == JOptionPane.CLOSED_OPTION || response == JOptionPane.CANCEL_OPTION) {
                return response;
            }
        }
        GuiPackage.getInstance().getIdeFrame().removeProject(project);
        GuiPackage.getInstance().updateMenuAndToolBar();
        KeywordRegistry.getInstance().unloadAllMacros();
        ResultCollector.getInstance().clear();
        return JOptionPane.YES_OPTION;
    }
}
